package com.xhwy.controller;

import com.xhwy.util.EnvironmentUtil;
import com.xhwy.util.R;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileController {

    //文件上传位置
    @Value("${file.staticPatternPath}")
    private String staticPatternPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

//    @Resource
//    Environment environment;


//    @PostMapping("/upload")
//    public R upload(@RequestPart("multipartFile") MultipartFile multipartFile) {
//        //file 效验
//        if(multipartFile.isEmpty()){
//            return R.fail("图片上传失败");
//        }
//        //file重命名：防止重名
//        String originalFilename = multipartFile.getOriginalFilename();//原来的图片名
//        String ext = "." + originalFilename.split("\\.")[1];
//        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//        String fileName = uuid + ext;
//        //上传图片
//        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//        //上传图片所在的相对路径
//        String relativePath = "\\images\\";
//        //上传图片所在的绝对路径
//        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static" + relativePath;
//        //完整路径
//        String path = pre + fileName;
//        try {
//            //将文件存入指定文件夹
//            multipartFile.transferTo(new File(path));
//            //创建返回数据的对象
//            R r = R.ok();
//            //获取项目的访问地址
//            String accessPath = EnvironmentUtil.getAccessPath(environment);
//            //保存完整路径和相对路径
//            r.put("url", (accessPath + relativePath + fileName).replace("\\", "/"));
//            r.put("relativePath", (relativePath + fileName).replace("\\", "/"));
//            return r;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return R.fail("图片上传失败");
//    }

    @PostMapping("/upload")
    public R upload(@RequestParam("multipartFile") MultipartFile multipartFile, HttpServletRequest request) {
        if(multipartFile.isEmpty()) {
            return R.fail("文件有误，上传失败！");
        }
        //获取文件类型
        String contentType = multipartFile.getContentType();
//        System.out.println(contentType);
        if(!(contentType.equals("image/png")||contentType.equals("image/jpeg")||contentType.equals("image/gif"))){
            return R.fail("文件格式错误，请上传图片");
        }

        //文件隔离，不同的文件放在不同的目录
        String dir = request.getParameter("dir");

        //源文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //截取文件名的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成唯一的文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-","") + suffix;
        //日期目录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = dateFormat.format(new Date());

        //指定上传目录
        File targetPath = new File(uploadFolder + dir,datePath);
        //判断目录是否存在，不存在则创建
        if (!targetPath.exists()) targetPath.mkdirs();
        //指定文件上传以后的真是名字
        File targetFileName = new File(targetPath, newFileName);

        try {
            //文件上传到指定目录
            multipartFile.transferTo(targetFileName);

            //图片访问路径
            String fileName = staticPatternPath.substring(1) + "/" + dir+ "/" + datePath + "/" + newFileName;
            return R.ok("上传成功").put("url", fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail("图片上传失败");
    }

//    @GetMapping("/download")
//    public ResponseEntity<byte[]> download(@RequestParam String fileName) {
//        try {
//            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
//            if(!path.exists()) {
//                path = new File("");
//            }
//            //进行下载逻辑
//            File upload = new File(path.getAbsolutePath(),"/upload/");
//
//            if(!upload.exists()) {
//                upload.mkdirs();
//            }
//            File file = new File(upload.getAbsolutePath()+"/"+fileName);
//            if(file.exists()){
//				/*if(!fileService.canRead(file, SessionManager.getSessionUser())){
//					getResponse().sendError(403);
//				}*/
//                HttpHeaders headers = new HttpHeaders();
//                //application/octet-stream
//                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//                headers.setContentDispositionFormData("attachment", fileName);
//                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
//    }

}
